#include	"SocketThread.h"

ThreadDataStruct	LocThreadData;
HANDLE	ThreadHandle;

DWORD WINAPI RecvThread( LPVOID lpParam ) 
{
	while (LocThreadData.GoOn)
	{
		if (LocThreadData.mySock.RecvData(&LocThreadData.bufDataIn) > 0)
		{	
			LocThreadData.event.EventType = irr::EET_LOG_TEXT_EVENT;
			LocThreadData.event.UserEvent.UserData1 = ISBCIMESSAGE;
			LocThreadData.event.UserEvent.UserData2 = (int)&LocThreadData.bufDataIn;
			LocThreadData.myDevice->postEventFromUser(LocThreadData.event); 
		}
	}

	return 0; 
} 

DWORD WINAPI SendThread( LPVOID lpParam ) 
{    
    return 0; 
} 

void CreateRecvThread(int *GoOn, SocketComm *mySock, LedDriver *myLed, IrrlichtDevice *myDevice)
{	
	DWORD	ThreadID;

	// Preparing the DataStruct for being passed to the ThreadFunction
	LocThreadData.GoOn = *GoOn;
	LocThreadData.mySock = *mySock;
	LocThreadData.myLed = *myLed;
	LocThreadData.myDevice = myDevice;
	// Done

	ThreadHandle = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)RecvThread, &LocThreadData, 0, &ThreadID);
}

void GetIncomingData(BCIMessage *buffer)
{
	//Inserire EnterCriticalRegion();
	memcpy(buffer,&LocThreadData.bufDataIn,sizeof(BCIMessage));
}

void ReleaseSocketThread(void)
{
	StopRecvThread();
	LocThreadData.mySock.Close();
	CloseHandle(ThreadHandle);
    //HeapFree(GetProcessHeap(), 0, &LocThreadData);
	ExitProcess(0);
}

void StopRecvThread(void)
{
	LocThreadData.GoOn = 0;
}

void StartRecvThread(void)
{
	LocThreadData.GoOn = 1;
}